﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using MySql.Data.MySqlClient;

namespace library
{
    public partial class bookInfo : Form
    {
        public bookInfo()
        {
            InitializeComponent();
        }

        string select_ISBN = "";

        private void bookInfo_Load(object sender, EventArgs e)
        {
            DataBind_Publisher();
            DataBind_book();
            int year = System.DateTime.Now.Year;
            int month = System.DateTime.Now.Month;
            int day = System.DateTime.Now.Day;
            pubDate_box.Value = new DateTime(year, month, day);
        }

        protected void DataBind_Publisher()
        {
            string sql = "select * from pubinfo";
            MySqlConnection conn = new MySqlConnection("server=localhost; database=librarysystem; UID=root; PWD = 123456; port = 3306");
            conn.Open();
            MySqlDataAdapter da = new MySqlDataAdapter(sql, conn);
            DataTable dt = new DataTable();
            da.Fill(dt);
            conn.Close();
            pubName_box.DataSource = dt;
            pubName_box.DisplayMember = "pubName";
            pubName_box.ValueMember = "pubNum";
        }

        protected void ClearTexBox()
        {
            bookName_box.Text = "";
            author_box.Text = "";
            version_box.Text = "";
            int year = System.DateTime.Now.Year;
            int month = System.DateTime.Now.Month;
            int day = System.DateTime.Now.Day;
            pubDate_box.Value = new DateTime(year, month, day);
            price_box.Text = "";
            brief_box.Text = "";
            ISBN_box.Text = "";
            pubName_box.SelectedIndex = 0;
        }

        protected void DataBind_book()
        {
            MySqlConnection conn = new MySqlConnection("server=localhost; database=librarysystem; UID=root; PWD = 123456; port = 3306");
            conn.Open();
            string str = "select * from bookinfo";
            MySqlDataAdapter da = new MySqlDataAdapter(str, conn);
            DataTable dt = new DataTable();
            da.Fill(dt);
            conn.Close();
            listView1.Items.Clear();
            foreach (DataRow dr in dt.Rows)
            {
                ListViewItem myitem = new ListViewItem(dr["ISBN"].ToString());
                myitem.SubItems.Add(dr["bookName"].ToString());
                myitem.SubItems.Add(dr["author"].ToString());
                MySqlConnection c = new MySqlConnection("server=localhost; database=librarysystem; UID=root; PWD = 123456; port = 3306");
                c.Open();
                string sql = string.Format("select pubName from pubinfo where pubNum = {0}", dr["pubNum"].ToString());
                MySqlDataAdapter a = new MySqlDataAdapter(sql, c);
                DataTable t = new DataTable();
                a.Fill(t);
                c.Close();
                DataRow r = t.Rows[0];
                myitem.SubItems.Add(r["pubName"].ToString());
                myitem.SubItems.Add(dr["version"].ToString());
                myitem.SubItems.Add(dr["pubDate"].ToString());
                myitem.SubItems.Add(dr["price"].ToString());
                myitem.SubItems.Add(dr["briefIntro"].ToString());
                myitem.SubItems.Add(dr["inventory"].ToString());
                myitem.SubItems.Add(dr["allInventory"].ToString());
                listView1.Items.Add(myitem); //将新建项添加到 ListView 控件中
            }

        }
        private void btn_save_Click(object sender, EventArgs e)
        {
            string bookName = bookName_box.Text.Trim();
            if (bookName == "")
            {
                MessageBox.Show("输入书名");
                return;
            }
            string author = author_box.Text.Trim();
            if (author == "")
            {
                MessageBox.Show("输入作者");
                return;
            }
            string version = version_box.Text.Trim();
            if (version == "")
            {
                MessageBox.Show("输入版本");
                return;
            }
          
            string price = price_box.Text.Trim();
            if (price == "")
            {
                MessageBox.Show("输入价格");
                return;
            }
            string brief = brief_box.Text.Trim();
            if (brief == "")
            {
                MessageBox.Show("输入书本简介");
                return;
            }
            string ISBN = ISBN_box.Text.Trim();
            if (lbl_note.Text.Trim() == "添加" && ISBN == "")
            {
                MessageBox.Show("输入书本ISBN");
                return;
            }
            string pubNum = pubName_box.SelectedValue.ToString();
            if (pubNum == "")
            {
                MessageBox.Show("选择出版社");
                return;
            }

            if (lbl_note.Text == "添加")
            {

                string sql = string.Format("INSERT INTO bookinfo (ISBN, bookName, author, pubNum, version, pubDate, price, briefIntro,inventory,allInventory) VALUES ('{0}', '{1}', '{2}', {3}, {4}, '{5}', {6}, '{7}',0,0)", ISBN,bookName,author,pubNum,version,pubDate_box.Value.ToString("yyyy-MM-dd"),price,brief);
                MySqlConnection conn = new MySqlConnection("server=localhost; database=librarysystem; UID=root; PWD = 123456; port = 3306");
                conn.Open();
                MySqlCommand cmd = new MySqlCommand(sql, conn);
                int i = cmd.ExecuteNonQuery();
                conn.Close();
                if (i > 0)
                {
                    MessageBox.Show("添加书本成功");
                    ClearTexBox(); //调用函数，清空各控件
                    DataBind_book();
                }
                else
                {
                    MessageBox.Show("添加书本失败");
                    return;
                }
            }
            else if (lbl_note.Text.Trim() == "修改")
            {
                MySqlConnection conn = new MySqlConnection("server=localhost; database=librarysystem; UID=root; PWD = 123456; port = 3306");
                conn.Open();

                string str = string.Format("update bookinfo set bookName = '{0}', author = '{1}',pubNum = {2}, version ={3},pubDate = '{4}',price = {5},briefIntro = '{6}' where ISBN = '{7}';",bookName,author,pubNum,version, pubDate_box.Value.ToString("yyyy-MM-dd"), price,brief,select_ISBN);
                MySqlCommand cmd = new MySqlCommand(str, conn);
                int i = cmd.ExecuteNonQuery();
                conn.Close();
                if (i > 0)
                {
                    MessageBox.Show("信息修改成功！");
                    DataBind_book(); //重新加载客户信息
                }
                else
                {
                    MessageBox.Show("信息修改失败！");
                }
                lbl_note.Text = "添加";
                ClearTexBox();
            }
        }

        private void pubDate_box_ValueChanged(object sender, EventArgs e)
        {

        }

        private void btn_cancel_Click(object sender, EventArgs e)
        {
            ClearTexBox();
        }

        private void return_btn_Click(object sender, EventArgs e)
        {
            this.Hide();
            Main frm = new Main();
            frm.Show();
        }

        private void delete_btn_Click(object sender, EventArgs e)
        {
            if (select_ISBN == "") //如果没有选中要删除的客户信息
            {
                MessageBox.Show("请先选择要删除的书本");
            }
            else
            {
                //弹出删除确认提示框
                DialogResult result = MessageBox.Show("确定要删除选中的书本吗？", "删除提示",
                MessageBoxButtons.YesNo, MessageBoxIcon.Question);
                if (result == DialogResult.Yes) //如果确定删除
                {
                    MySqlConnection conn = new MySqlConnection("server=localhost; database=librarysystem; UID=root; PWD = 123456; port = 3306");
                    conn.Open();
                    string str = string.Format("select allInventory from bookinfo where ISBN ={0}", select_ISBN);
                    MySqlDataAdapter da = new MySqlDataAdapter(str, conn);
                    DataTable dt = new DataTable();
                    da.Fill(dt);
                    conn.Close();
                    DataRow dr = dt.Rows[0];
                    if (Convert.ToInt32(dr["allInventory"].ToString()) > 0)
                    {
                        MessageBox.Show("请先清空库存，再删除书本");
                        return;
                    }
                    MySqlConnection c = new MySqlConnection("server=localhost; database=librarysystem; UID=root; PWD = 123456; port = 3306");
                    c.Open();
                    string sql = string.Format("delete from bookinfo where ISBN ='{0}'", select_ISBN);
                    MySqlCommand cmd = new MySqlCommand(sql, c);
                    int i = cmd.ExecuteNonQuery();
                    c.Close();
                    if (i > 0)
                    {
                        MessageBox.Show("删除成功");
                        ClearTexBox();
                        DataBind_book();
                    }
                    else
                    {
                        MessageBox.Show("信息删除失败！");
                    }
                    select_ISBN = "";
                }
            }
        }

        private void listView1_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (listView1.SelectedItems.Count > 0) //如果有选中项
            {
                ListViewItem myitem = listView1.SelectedItems[0]; //获取选中的第一行（一次只能选一行）
               
                bookName_box.Text = myitem.SubItems[1].Text;
                author_box.Text = myitem.SubItems[2].Text;
                pubName_box.Text = myitem.SubItems[3].Text;
                version_box.Text = myitem.SubItems[4].Text;
                int year = Convert.ToInt32(myitem.SubItems[5].Text.Split(' ')[0].Split('/')[0]);
                int month = Convert.ToInt32(myitem.SubItems[5].Text.Split(' ')[0].Split('/')[1]);
                int day = Convert.ToInt32(myitem.SubItems[5].Text.Split(' ')[0].Split('/')[2]);
                pubDate_box.Value = new DateTime(year, month, day);
                price_box.Text = myitem.SubItems[6].Text;
                brief_box.Text = myitem.SubItems[7].Text;
                lbl_note.Text = "修改";
                select_ISBN = myitem.SubItems[0].Text;
            }
        }
    }
}
